package com.happycat.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.happycat.Pagination;
import com.happycat.ResponseHeaderModel;
import com.happycat.ResponseModel;
import com.happycat.SysContants;
import com.happycat.base.R;
import com.happycat.base.context.BaseContextHandler;
import com.happycat.base.exception.RestApiException;
import com.happycat.console.model.CatGift;
import com.happycat.console.service.ISocialTransService;
import com.happycat.mapper.CatGiftMapper;
import com.happycat.mapper.UserGiftDetailMapper;
import com.happycat.mobile.dto.UserGetFreeGiftSaveDto;
import com.happycat.mobile.dto.UserGiveGiftSaveDto;
import com.happycat.mobile.model.UserAccount;
import com.happycat.mobile.model.UserGiftDetail;
import com.happycat.mobile.service.UserAccountService;
import com.happycat.mobile.service.UserGiftDetailService;
import com.happycat.social.entity.SocialTrans;
import com.happycat.utils.StrPool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Module: UserGiftDetail.java
 * 
 * @author liaoyong
 * @since JDK 1.8
 * @version 1.0
 * @date 2020-08-01
 * @Descriptions:
 */
@Service
@Slf4j
public class UserGiftDetailServiceImpl extends ServiceImpl<UserGiftDetailMapper, UserGiftDetail> implements UserGiftDetailService {

    @Autowired
    private CatGiftMapper catGiftMapper;
    @Autowired
    private UserAccountService userAccountService;
    @Autowired
    private ISocialTransService socialTransService;

 	public ResponseModel<UserGiftDetail> selectOne(UserGiftDetail userGiftDetail){
 		Wrapper<UserGiftDetail> queryWrapper = new QueryWrapper<>(userGiftDetail);
		ResponseModel<UserGiftDetail> responseModel = new ResponseModel<>();
		responseModel.setCode(SysContants.SYS_SUCCESS_CODE);
		responseModel.setMessage("查询成功");
		responseModel.setData(getOne(queryWrapper));
		return responseModel;
 	
 	}
	
	public ResponseHeaderModel	add(UserGiftDetail userGiftDetail){
		ResponseHeaderModel responseHeaderModel = new ResponseHeaderModel();
		
		boolean result = save(userGiftDetail);
		if(result) {
			responseHeaderModel.setCode(SysContants.SYS_SUCCESS_CODE);
			responseHeaderModel.setMessage("新增成功");
		}else {
			responseHeaderModel.setCode(SysContants.SYS_FAIL_CODE);
			responseHeaderModel.setMessage("新增失败");
		}
		return responseHeaderModel;
	}
	
	public ResponseHeaderModel	modify(UserGiftDetail userGiftDetail){
			ResponseHeaderModel responseHeaderModel = new ResponseHeaderModel();
		
		boolean result = updateById(userGiftDetail);
		if(result) {
			responseHeaderModel.setCode(SysContants.SYS_SUCCESS_CODE);
			responseHeaderModel.setMessage("修改成功");
		}else {
			responseHeaderModel.setCode(SysContants.SYS_FAIL_CODE);
			responseHeaderModel.setMessage("修改失败");
		}
		return responseHeaderModel;
	}
	
	public ResponseModel<Page<UserGiftDetail>> pageList(Pagination<UserGiftDetail>page){
		ResponseModel<Page<UserGiftDetail>> responseModel = new ResponseModel<>();
		responseModel.setCode(SysContants.SYS_SUCCESS_CODE);
		responseModel.setMessage("查询成功");
		responseModel.setData(page(page,new QueryWrapper<UserGiftDetail>(page.getEntity())));
		return responseModel;
	}

    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public UserGiftDetail receiveFreeGift(UserGetFreeGiftSaveDto dto) {
        //校验礼物是否存在是否有效
        CatGift catGift = catGiftMapper.selectById(dto.getGiftId());
        if(catGift==null || catGift.getStatus().longValue()!=1){
            log.error("礼物不存在或不可用, giftId:{}", dto.getGiftId());
            throw new RestApiException(R.fail(-1, "礼物不存在或不可用"));
        }
        //校验是否免费礼物
        if(!catGift.getGiftType().equals("2")){
            log.error("非免费礼物，无法免费领取, giftId:{}", dto.getGiftId());
            throw new RestApiException(R.fail(-1, "非免费礼物"));
        }

        UserGiftDetail detail = BeanUtil.copyProperties(dto, UserGiftDetail.class);
//        detail.setReceiverId();// 从上下文获取

        detail.setGiveId(0L);// 系统
        detail.setCreateTime(new Date());

        //新增礼物关联用户关系
        if(save(detail)){
            //TODO 新增交易流水
            //新增交易流水
            SocialTrans trans = new SocialTrans();
            trans.setCreateTime(new Date());
            trans.setUpdateTime(new Date());
            trans.setPayUserId(detail.getGiveId());
            trans.setPayAccountId(detail.getGiveId());
            trans.setReceiveUserId(detail.getReceiverId());
            trans.setReceiveAccountId(detail.getReceiverId());
            trans.setTransType("2");
            trans.setTransNo(System.currentTimeMillis() + RandomUtil.randomNumbers(5));//流水号
            trans.setPayAmount(new BigDecimal(dto.getGiftNumber() + ""));
            trans.setPayAmountType("0");
            trans.setPayTime(new Date());
            trans.setStatus(SocialTrans.STATUS_PAID);

            trans.setPayChannel(0);
            trans.setExtra1(catGift.getGiftType()+"");
            trans.setExtra2(catGift.getName());
            socialTransService.save(trans);

            return detail;
        }else
            throw new RestApiException(R.fail(-1, "领取失败"));
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public Boolean giveGift(UserGiveGiftSaveDto dto) {
 	    if(dto.getGiftNumber()==null || dto.getGiftNumber().intValue()<1){
            throw new RestApiException(R.fail(-1, "赠送数量不能小于1"));
        }
        //校验礼物是否存在是否有效
        //获取礼物
        CatGift catGift = catGiftMapper.selectById(dto.getGiftId());
        if(catGift==null || catGift.getStatus().longValue()!=1){
            log.error("礼物不存在或不可用, giftId:{}", dto.getGiftId());
            throw new RestApiException(R.fail(-1, "礼物不存在或不可用"));
        }

//        dto.setGiveId();
        // 从上下文获取
        dto.setGiveId(BaseContextHandler.getUserId());

        UserAccount userAccount = userAccountService.getById(dto.getGiveId());
        if(userAccount==null || userAccount.getStatus()==null || userAccount.getStatus()!=1){
            log.error("赠送方不存在或状态不正常, giveId:{}", dto.getGiveId());
            throw new RestApiException(R.fail(-1, "赠送方不存在或状态不正常"));
        }

        if("1".equals(catGift.getGiftType())){
            //特权礼物
            //TODO 校验赠送方是否拥有该特权
        }

        List<Long> receiverIds = new ArrayList<>();
        Arrays.stream(dto.getReceiverIds().split(StrPool.COMMA)).forEach(e -> receiverIds.add(Long.parseLong(e)));
        //礼物耗费币数量
        int giftSum = receiverIds.size() * dto.getGiftNumber().intValue();
        long totalSum = catGift.getFoodNumber().longValue() * giftSum;

        //校验赠送方余额是否充足
        if(userAccount.getBalance()==null || userAccount.getBalance().compareTo(totalSum * 1.0) < 0){
            log.error("用户余额不足，当前余额:{}, 赠送所需数量:{}", userAccount.getBalance(), totalSum);
            throw new RestApiException(R.fail(-1, "余额不足"));
        }

        receiverIds.forEach(receiveId -> {
            UserGiftDetail detail = BeanUtil.copyProperties(dto, UserGiftDetail.class);
            detail.setCreateTime(new Date());
            detail.setReceiverId(receiveId);
            List<String> transIds = new ArrayList<>();
            //新增礼物关联用户关系
            if(save(detail)){
                //新增交易流水
                SocialTrans trans = new SocialTrans();
                trans.setRoomId(dto.getRoomId());
                trans.setRoomName(dto.getRoomName());
                trans.setPayUserId(detail.getGiveId());
                trans.setPayAccountId(detail.getGiveId());
                trans.setReceiveUserId(detail.getReceiverId());
                trans.setReceiveAccountId(detail.getReceiverId());
                trans.setTransType("2");
                trans.setTransNo(System.currentTimeMillis() + RandomUtil.randomNumbers(5));//流水号
                trans.setPayAmount(new BigDecimal(giftSum + ""));
                trans.setPayAmountType("0");
                trans.setPayTime(new Date());
                trans.setStatus(SocialTrans.STATUS_PAID);

                trans.setPayChannel(0);
                trans.setExtra1(catGift.getGiftType()+"");
                trans.setExtra2(catGift.getName());
                trans.setExtra3(catGift.getId()+"");
                socialTransService.save(trans);

                transIds.add(trans.getId()+"");
            }

            if(totalSum!=0){
                //新增账户变动流水, 修改余额, 增加经验值
                userAccountService.updateBalance(userAccount.getId(), totalSum, 2, String.join(StrPool.COMMA,
                        transIds), 0, catGift.getExperience()==null?0:catGift.getExperience());
            }
        });

        return true;
    }

}
